package com.icepeach.icepeachhomeback.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icepeach.icepeachhomeback.common.RelationEnum;
import com.icepeach.icepeachhomeback.convert.RelationConvert;
import com.icepeach.icepeachhomeback.entity.Menu;
import com.icepeach.icepeachhomeback.entity.Menu;
import com.icepeach.icepeachhomeback.entity.Relation;
import com.icepeach.icepeachhomeback.mapper.RelationMapper;
import com.icepeach.icepeachhomeback.req.MenuListQueryReq;
import com.icepeach.icepeachhomeback.service.MenuService;
import com.icepeach.icepeachhomeback.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
        implements MenuService {

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<String> queryMenuListByRole(String roleId) {
        List<Relation> relations = relationMapper.queryRelationListByTargetId(RelationEnum.ROLE_MENU.getBusinessType(), RelationEnum.ROLE_MENU.getTargetType(), roleId);
        return relations.stream().map(Relation::getBusinessId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<Menu> convertMenuToTree(List<String> menuIds) {
        List<Menu> menus = menuMapper.selectBatchIds(menuIds);
        return convertToTree(menus, null);
    }

    @Override
    public List<Menu> convertToTree(List<Menu> menus, String parentId) {
        List<Menu> list = new ArrayList<>();
        if (CollectionUtil.isEmpty(menus)) {
            return list;
        }
        menus.forEach(item -> {
            if (Objects.equals(item.getParentId(), parentId)) {
                List<Menu> children = convertToTree(menus, item.getId());
                if (CollectionUtil.isNotEmpty(children)) {
                    item.setChildren(children);
                }
                list.add(item);
            }
        });
        return list;
    }

    public static void main(String[] args) {
        String a = null;
        String b = null;
        System.out.println(Objects.equals(a, b));
    }
}
